package com.yangyongchao.resumedownload.service;

import android.content.Context;

import com.yangyongchao.resumedownload.db.ThreadDAO;
import com.yangyongchao.resumedownload.db.ThreadDaoImpl;
import com.yangyongchao.resumedownload.entires.FileInfo;
import com.yangyongchao.resumedownload.entires.ThreadInfo;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by 杨永超的电脑 on 2017/9/9.
 * 下载任务类
 */

public class DownloadTask {

    private Context mContext = null;
    private FileInfo mFileInfo = null;
    private ThreadDAO mDao = null;

    public DownloadTask(Context mContext, FileInfo mFileInfo) {
        this.mContext = mContext;
        this.mFileInfo = mFileInfo;
        mDao = new ThreadDaoImpl(mContext);
    }

    /**
     * 下载线程
     */
    class DownloadThread extends Thread{
        private ThreadInfo mThreadInfo = null;

        public DownloadThread(ThreadInfo mthreadInfo){
            this.mThreadInfo = mthreadInfo;
        }
        public void run(){
            //想数据库中插入线程细心
            if (mDao.isExisti(mThreadInfo.getUrl(),mThreadInfo.getId())){
                mDao.insertThread(mThreadInfo);
            }
            HttpURLConnection conn;
            //设置下载位置
            try {
                URL url = new URL(mThreadInfo.getUrl());
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5*1000);
                conn.setRequestMethod("GET");
                //设置下载位置
                int start = mThreadInfo.getStart()+mThreadInfo.getFinished();
                conn.setRequestProperty("Range","bytes="+start+"-"+mThreadInfo.getEnd());
                //设置文件写入位置
                File file = new File(DownloadSrevice.DOWNLOAD_PATH,mFileInfo.getFileName());
                RandomAccessFile raf = new RandomAccessFile(file,"rwd");
                raf.seek(start);
                //开始下载
                //读取数据
                //写入文件
                //下载暂停时保存下载进度
                //把下载进度发送广播给Activity
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
